package com.neusoft.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @Author：ljz
 * @Date：2022/8/17 14:58
 * @Description: 前端控制器
 */
@WebServlet("/")
// /* .html等其他也会拦截
public class DispatcherServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        //约定大于配置 自定义前端控制器 拦截url格式要求： /控制器类名/控制器方法名
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //编码处理
        String path = request.getServletPath();
        String className = path.substring(1, path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/") + 1);
        PrintWriter out = null;
        try {
            //利用反射
            Class clazz = Class.forName("com.neusoft.elm.controller." + className);
            Object controller = clazz.newInstance();
            Method method = clazz.getMethod(methodName, new Class[]{HttpServletRequest.class});//后面是参数
            Object result = method.invoke(controller, new Object[]{request});
            out = response.getWriter();
            ObjectMapper om = new ObjectMapper();
            //向客户端响应json数据
            out.print(om.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DispatcherServlet信息：请求url：" + path);
            System.out.println("DispatcherServlet信息：类名：" + className + "\t方法名：" + methodName);
        } finally {
            out.close();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
}
